<?php
/*************************************
 *
 * @Base 基类控制器~封装成功失败返回格式
 *
 ************************************/
namespace app\api\controller;

use think\Controller;
use think\Session;
use think\exception\HttpResponseException;
use think\Request;
use \UnexpectedValueException;
use think\Response;
use think\Env;
use think\config;
use think\Validate;

class Base extends Controller
{
    protected $Request;

    protected $fileName = 'AppkeyConfig.php';

    public function __construct
    (
        Request $request
    )
    {

    }
    public function checkOust($respons)
    {
        $validate = new Validate([
            'time'  => 'require',
            'token' => 'require',
        ]);

        if (!$validate->check($respons)) {
            return ['data'=>$validate->getError(), 'status_code' => 400];
        }
        //token验证
        $fileName =$this->fileName;
        if ($fileName) {
            $apikeyconfig = Config::load(APP_PATH.'/common/config/'.$fileName);
            $keyconf = $apikeyconfig['xcxappkey'];
            $appkey =  $keyconf['key'];
            $time = $respons['time'];
            if ($respons['token'] != strtoupper(md5($appkey . $time))) {
                return ['data'=>'Token认证失败！'];
            }
        }
    }

    /**
     *  api 设置响应头返回值
     *  $param Array $data 返回值
     *  $param int  $code  设置响应头状态码
     */
    public function errorHttpResult($data, $code)
    {
        return json($data, $code);
    }

    /**
     * api 错误结果响应
     * @param $code
     * @param $msg
     */
    protected function errorResult($code, $msg)
    {
        $this->returnResult([
            'status_code' => $code,
            'data'  => $msg,
        ]);
    }

    /**
     * api 成功结果响应
     * @param $code
     * @param $msg
     */
    protected function successResult($code, $data,$extra=array())
    {
        $newarray = [
            'code' => 0,
            'data' => $data,
            'time' => $_SERVER['REQUEST_TIME']
        ];
        if (is_array($extra)) {
            foreach ($extra as $key => $value) {
                $newarray[$key]=$value;
            }
        }
        $this->returnResult([
            'status_code' => $code,
            'data'  => $data,
//            'time' => $_SERVER['REQUEST_TIME']
        ]);

    }

    /**
     * 返回封装后的API数据到客户端
     * @param $result
     * @param array $header
     */
    protected function returnResult($result, $type = '', array $header = [])
    {
        $type = $type ?: $this->getResponseType();

        $response = Response::create($result, $type)->header($header);

        throw new HttpResponseException($response);
    }
}